package middlewares

import (
	"github.com/gin-gonic/gin"
	"moko/utility"
	"net/http"
	"strings"
)

// 假设你有一个函数来验证 JWT 令牌
func validateJWT(token string) bool {
	// 解析token内容
	_, err := utility.ParseToken(nil, token)
	if err != nil {
		return false
	}

	return true
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "未登录"})
			c.Abort()
			return
		}

		token := strings.TrimPrefix(authHeader, "Bearer ")
		if !validateJWT(token) {
			c.JSON(http.StatusUnauthorized, gin.H{"code": http.StatusUnauthorized, "msg": "登录已失效"})
			c.Abort()
			return
		}

		// 如果验证通过，继续处理请求
		c.Next()
	}
}
